package com.rwb.springboot.sell.cenverter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rwb.springboot.sell.dto.OrderDTO;
import com.rwb.springboot.sell.enums.ResultEnum;
import com.rwb.springboot.sell.exception.MallException;
import com.rwb.springboot.sell.form.OrderForm;
import com.rwb.springboot.sell.vo.OrderDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ruwenbo on 2018/1/2.
 */
public class OrderForm2OrderDTOConverter {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderForm2OrderDTOConverter.class);

    public static OrderDTO converter(OrderForm orderForm) {
        Gson gson = new Gson();
        OrderDTO orderDTO = new OrderDTO();

        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
        try {
            orderDetails = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>(){}.getType());
        } catch (Exception e) {
            LOGGER.error("【参数转换】错误,items={}", orderForm.getItems());
            throw new MallException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetails);
        return orderDTO;
    }
}
